package com.zimmur.interceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.alibaba.fastjson.JSON;
import com.zimmur.common.StatusCodeEnum;
import com.zimmur.controller.BaseController;
import com.zimmur.model.account.User;
import com.zimmur.service.IUserService;
import com.zimmur.service.RedisCacheUtil;
import com.zimmur.tools.JsonEntity;
import com.zimmur.tools.JwtTokenUtil;
import com.zimmur.tools.RequestAuthorVerify;

public class RequestHeadersInterceptor extends HandlerInterceptorAdapter {
	private Logger log = LoggerFactory.getLogger(RequestHeadersInterceptor.class);
	@Resource
    private	IUserService userService;
	@Resource
	private JwtTokenUtil jwttokenUtil;
	
	@Resource
	private RedisCacheUtil<String> redisCacheUtil;
	
	@Value("#{spingMvcProperties['System.GuestId']}")
	private String guessUserId;
	@Value("#{spingMvcProperties['public.key']}")
	private String publicKey;
		
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		request.setCharacterEncoding("utf-8");
		response.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=UTF-8"); 		
		JsonEntity entity = new JsonEntity(StatusCodeEnum.CODE100404);
		log.debug(request.getContentLength()+""); 		
		//时间戳验证
        String timestamp = request.getHeader("timestamp");
        if(StringUtils.isEmpty(timestamp)){        	
        	response.getWriter().write(JSON.toJSONString(entity));
        	return false;
        }
        entity = new JsonEntity(StatusCodeEnum.CODE100402);
        try {
        	long requestTime = Long.parseLong(timestamp);
	        long curTime = System.currentTimeMillis();
	        if((curTime - requestTime) > 10 * 60 * 1000){
	        	response.getWriter().write(JSON.toJSONString(entity));
	            return false;
	        }
		} catch (Exception e) {
			log.error(e.getMessage());
			entity = new JsonEntity(StatusCodeEnum.CODE100000);
			response.getWriter().write(JSON.toJSONString(entity));
		}
        //验证公钥
        entity = new JsonEntity(StatusCodeEnum.CODE100403);
        String key;
		if(redisCacheUtil.exists(publicKey)){
			key = redisCacheUtil.getCacheString(publicKey);
		}else{
			response.getWriter().write(JSON.toJSONString(entity));
        	return false;
		}
        
        entity = new JsonEntity(StatusCodeEnum.CODE100401);
      //sign = 用户ID + ":" + 签名
		String userSign = request.getHeader("sign");
		if(userSign == null || userSign.equals("") || userSign.indexOf(":")==-1){
			response.getWriter().write(JSON.toJSONString(entity));
			return false;
		}
		String[] signArr = userSign.split(":");
		if(signArr.length != 2){
			response.getWriter().write(JSON.toJSONString(entity));
			return false;
		}
		String sign = signArr[1];
		String userId = signArr[0];
		if(userId.startsWith("\"")){
			userId=userId.replace("\"", "");
		}		
		if(userId == null || userId.equals("") ){
			response.getWriter().write(JSON.toJSONString(entity));
			return false;
		}
		Long uId;
		//是否为游客
		if(userId.equals(guessUserId)){
			uId=Long.parseLong(guessUserId);
			String token = request.getParameter("token");
			long token_userId= jwttokenUtil.getUserId(token);
			if(uId != token_userId){
				response.getWriter().write(JSON.toJSONString(entity));
	        	return false;
			}
			if(token==null || token =="" ){
				response.getWriter().write(JSON.toJSONString(entity));
	        	return false;
			}
			/*String content=RequestAuthorVerify.checkAuthorTest(request, sign, token, key);
			if(content!=null){
				entity.setData(content);
				response.getWriter().write(JSON.toJSONString(entity));
	        	return false;
			}*/
			if(!RequestAuthorVerify.checkAuthor(request,sign,token,key)){
		        	response.getWriter().write(JSON.toJSONString(entity));
		        	return false;
		       }
		}else{
			try {
				uId = Long.parseLong(userId);
				User user= userService.getUserInfoByUserId(uId);
				if(user == null){
					response.getWriter().write(JSON.toJSONString(entity));
					return false;
				}
				String authToken = userService.getUserToken(user);
		        if(!RequestAuthorVerify.checkAuthor(request,sign,authToken,key)){
		        	response.getWriter().write(JSON.toJSONString(entity));
		        	return false;
		        }
				
			} catch (Exception e) {
				log.error(e.getMessage());
				entity = new JsonEntity(StatusCodeEnum.CODE100000);
				response.getWriter().write(JSON.toJSONString(entity));
			}
		}
		
		
		
        
		BaseController.setRequest(request);
		BaseController.setResponse(response);
		return true;
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
	}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler,
			Exception ex) throws Exception {
		BaseController.removeRequest();
		BaseController.removeResponse();
	}
	
}
